package br.com.sigde.framework.exception.handler;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;

import br.com.sigde.framework.exception.LogicException;

public class ErrorHandler {

	
	public static void handleException (FacesContext fe, Exception e) throws Exception{
		
		//String view = fe.getViewRoot().getViewId();
		//HttpServletRequest request = (HttpServletRequest) fe.getExternalContext().getRequest();
		///HttpServletResponse response = (HttpServletResponse) fe.getExternalContext().getResponse();
		LogicException be = getBusinessRootCause(e);
		if(be==null){
			throw e;
		}
		FacesMessage message = new FacesMessage(be.getMessage());
		fe.addMessage("erros", message);
		/*try{
		//request.getRequestDispatcher(view).forward(request, response);
		}catch(Exception ex){
			e.printStackTrace();
		}*/
	}
	
	private static LogicException getBusinessRootCause(Exception e)  {
		Exception c = null;
		try{
		c = (Exception) e.getCause();
		}catch(ClassCastException ex){
			return null;
		}
		if(c==null){
			return (LogicException) c;
		}
		if(c instanceof LogicException){
			return (LogicException)c;
		}else{
			return getBusinessRootCause(c);
		}
	}

	public static void handleThrowable(FacesContext fe, Throwable t) throws Throwable{
		throw t;
	}
}
